<!--
 * @Author: doing
 * @Date: 2023-08-10 10:21:33
 * @LastEditors: git config user.name && git config user.email
 * @LastEditTime: 2023-08-31 20:08:44
 * @FilePath: \background-management-system\src\pages\role\index.vue
 * @Description: 
 * 角色管理页面
 * Copyright (c) 2023 by 1540265624@qq.com, All Rights Reserved. 
-->
<template>
    <div>
        <!-- 卡片视图区域 -->
        <el-card v-loading="isRoleListLoading">
            <el-form ref="searchRef" :model="searchForm">
                <el-form-item label="角色名称" prop="name">
                    <el-input style="width: 150px;" v-model="searchForm.name"></el-input>
                    <el-button type="primary" @click="findRole" class="ml-4" v-permission="['role:search']">
                        <el-icon style="vertical-align: middle;">
                            <search />
                        </el-icon>
                        <span style="vertical-align: middle;">查询</span>
                    </el-button>
                    <el-button @click="resetRoleList" class="ml-2">
                        <el-icon style="vertical-align: middle;">
                            <RefreshLeft />
                        </el-icon>
                        <span style="vertical-align: middle;">重置</span>
                    </el-button>
                    <el-button type="primary" @click="handleAdd" class="ml-2" v-permission="['role:add']">
                        <el-icon style="vertical-align: middle;">
                            <CirclePlus />
                        </el-icon>
                        <span style="vertical-align: middle;">新增</span>
                    </el-button>
                </el-form-item>
            </el-form>
                <el-table ref="assignTableRef" :data="assignTable" @select-all="selectAll" border :table-layout="tableLayout" :cell-style="{ textAlign: 'center' }" :header-cell-style="{textAlign: 'center'}">
                    <el-table-column property="id" label="序号" max-width="20px" />
                    <el-table-column property="name" label="角色名称" />
                    <el-table-column property="remark" label="备注" />
                    <el-table-column label="更新时间" prop="updateDate">
                        <template  #default="{ row }">
                            {{ formatTime(row.updateDate) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="auto" min-width="200px">
                        <template v-slot="scope">
                            <el-row :gutter="20" :offset="10" class="flex justify-center">
                                <el-button @click="assignMenu(scope.row)" class="btn" type="primary" v-permission="['role:permission']">
                                    <el-icon style="vertical-align: middle;">
                                        <Setting />
                                    </el-icon>
                                    <span style="vertical-align: middle;">分配权限</span>
                                </el-button>
                                <el-button @click="handleEdit(scope.row)" class="btn" type="success"  v-permission="['role:edit']">
                                    <el-icon style="vertical-align: middle;">
                                        <Edit />
                                    </el-icon>
                                    <span style="vertical-align: middle;">编辑</span>
                                </el-button>
                                <el-button @click="roleDelete(scope.row.id)" type="danger"  v-permission="['role:delete']">
                                    <el-icon style="vertical-align: middle;">
                                        <Delete />
                                    </el-icon>
                                    <span style="vertical-align: middle;">删除</span>
                                </el-button>
                            </el-row>
                        </template>
                    </el-table-column>
                </el-table>

            <!-- 分页功能开始 -->
            <el-pagination v-model:current-page="page.current" v-model:page-size="page.size"
                :page-sizes="[20, 50, 100]" :disabled="disabled" :background="background"
                layout="total, sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
            <!-- 分页功能结束 -->

        </el-card>
        <!-- 分配菜单权限组件开始 -->
        <form-drawer ref="assignMenuRef" :title="assignMenuTitle" destroyOnClose @submit="roleMenuSubmit">
            <el-tree-v2 ref="elTreeRef" node-key="id" :check-strictly="checkStrictly"
                :default-expanded-keys="defaultExpandedKeys" :data="ruleList"
                :props="{ label: 'name', children: 'children' }" show-checkbox :height="treeHeight" @check="handleTreeCheck"
                v-loading="isMenuTreeLoading">
                <template #default="{ node, data }">
                    <div class="flex items-center">
                        <el-tag :type="type(data)">{{ typeText(data) }}</el-tag>
                        <span class="ml-2 text-sm"> {{ data.name }} </span>
                    </div>
                </template>
            </el-tree-v2>
        </form-drawer>
        <!-- 分配菜单权限组件结束 -->

        <!-- 编辑角色信息开始 -->
        <form-drawer ref="formDrawerRef" :title="drawerTitile" :destroyOnClose="true" @submit="drawerSubmit"
            @clean="cleanForm">
            <el-form :rules="rules" ref="formRef" :model="formDrawerData" label-width="100px" label-position="right"
                style="width: 400px">
                <el-form-item label="角色名字：" prop="name">
                    <el-input v-model="formDrawerData.name" />
                </el-form-item>
                <el-form-item label="角色备注：" prop="remark">
                    <el-input v-model="formDrawerData.remark" />
                </el-form-item>
            </el-form>
        </form-drawer>
        <!-- 编辑角色信息结束 -->

    </div>
</template>
<script setup>
import { ref, onMounted, reactive, computed, nextTick } from 'vue'
import {
    getMenuids,
    getMenus,
    searchRole,
    updataRole,
    addRole,
    updataRoleMenu,
    deleteRole
} from '~/api/role.js'
import {
    showModal,
    toast,
    formatTime
} from '~/composables/util.js'
import FormDrawer from '~/components/FormDrawer.vue'


//初始化角色表格开始
const assignTableRef = ref(null)
const assignTable = ref([])
const isRoleListLoading = ref(false)
const tableLayout = ref('auto')
const isAddOrEdit = ref(true)
const searchRef = ref(null)
const searchForm = reactive({})
const page = reactive({
    current: 1,
    size: 20,
    total: 0
})
onMounted(async () => {
    await InitRole()
})

//查询角色
const findRole = async function () {
    page.current = 1
    InitRole()
}

//初始化数据函数
const InitRole = async function () {

    const body = {...page,...searchForm}
    console.log('传递的参数是')
    console.log(body)
    
    isRoleListLoading.value = true
    //获取用户信息列表
    await searchRole(body).then(res=>{
        assignTable.value = res.data.data.records
        page.total = res.data.data.total
    })
    isRoleListLoading.value = false
}

const select = function () {
    assignTable.value.forEach(t => {
        assignTableRef.value.toggleRowSelection(t, t.checked)
    })
}
const selectAll = function (row) {
    assignTable.value.forEach(t => {
        t.checked = !!row[0]
    })
}

//初始化角色表格结束

//分页内容开始(待开发)
const disabled = ref(false)
const background = ref(true)

const handleSizeChange = async function (e) {
    InitRole()
}
const handleCurrentChange = async function (e) {
    InitRole()
}
//分页内容结束(待开发)



//操作栏开始
//分配权限
const isMenuTreeLoading = ref(false)
const assignMenuRef = ref(null)
const assignMenuTitle = ref('分配权限')
const menuids = ref([])
const targetmenuids = ref([])

const elTreeRef = ref(null)
const checkStrictly = ref(false)
const ruleList = ref([])
const treeHeight = ref(0)
const roleId = ref(0)
//造一个假数据,防止数据延迟
const defaultExpandedKeys = ref([])
const typeText = computed(()=>{
    return function(res){
        if(res.type === 1){
            return '目录'
        }else if(res.type === 2){
            return '菜单'
        }else{
            return '按钮'
        }
    }
})
const type = computed(()=>{
    return function(res){
        if(res.type === 1){
            return 'success'
        }else if(res.type === 2){
            return 'warning'
        }else{
            return 'info'
        }

    }
})


const assignMenu = async function (row) {
    //打开
    assignMenuRef.value.hideLoading()
    assignMenuRef.value.open()
    //开始加载样式
    isMenuTreeLoading.value = true

    await nextTick(()=>{
        roleId.value = row.id
        treeHeight.value = window.innerHeight - 180
        checkStrictly.value = true
    })

    
    //获取到所有的菜单权限
    await getMenus({name:''}).then(async(res) => {
        console.log(res)
        //设置默认展开的节点
        ruleList.value = res.data.data.data
        
        await setTimeout(function(){
            res.data.data.data.forEach(item=>{
                defaultExpandedKeys.value.push(item.id)
            })
        },2000)
        console.log(defaultExpandedKeys.value)
        console.log('菜单权限列表')
        console.log(res.data.data.data)
    }).catch(err=>{
        console.log(err)
    })
    
    //根据id获取到当前用户所有的菜单权限(从最开始的用户登录的时候就获取到了)
    await getMenuids(row.id).then(async (res) => {
        menuids.value = res.data.data
        await setTimeout(() => {
            //将数组中的id值和对对应的checked设置为true
            elTreeRef.value.setCheckedKeys(menuids.value, true)
            console.log('当前角色所拥有的菜单权限集合')
            console.log(menuids.value)
            targetmenuids.value = [...menuids.value]
            checkStrictly.value = false
        }, 150);
    })


    isMenuTreeLoading.value = false
}

//监听
const handleTreeCheck = (...e) => {
    const { checkedKeys, halfCheckedKeys } = e[1]
    targetmenuids.value = checkedKeys.concat(halfCheckedKeys)
    console.log(targetmenuids.value)
}



//提交
const roleMenuSubmit = async function () {
    console.log('角色id为' + '\t' + roleId.value)
    console.log('菜单权限id数组')
    console.log(targetmenuids.value)
    assignMenuRef.value.showLoading()
    await updataRoleMenu(roleId.value, targetmenuids.value).then(res => {
        assignMenuRef.value.hideLoading()
        toast('更新成功')
        //分页至于第一页
        resetRoleList()
    }).catch(err=>{
        console.log(err)
    }).finally(() => {
        assignMenuRef.value.close()
    })
}


//分配角色结束

//编辑角色开始
const formDrawerRef = ref(null)
const formRef = ref(null)
const formDrawerData = reactive({})
const drawerTitile = ref('')

//表单验证规则
const rules = {
    username: [
        {
            required: true,
            message: '用户名不能为空',
            trigger: 'blur'
        },
    ],
    nickName: [
        {
            required: true,
            message: '昵称不能为空',
            trigger: 'blur'
        },
    ],
    mobile: [
        {
            required: true,
            message: '电话号码不能为空',
            trigger: 'blur'
        },
    ],
    email: [
        {
            required: true,
            message: '邮箱不能为空',
            trigger: 'blur'
        },
    ],
}



//打开抽屉
const handleEdit = async function (item) {
    console.log(item)
    isAddOrEdit.value = false
    formDrawerRef.value.open()
    await nextTick(()=>{
        formDrawerData.id = item.id
        formDrawerData.name = item.name
        formDrawerData.remark = item.remark
    }) 
}

const handleAdd = async function(){
    console.log(formDrawerData)
    isAddOrEdit.value = true

    formDrawerRef.value.open()
    formDrawerRef.value.hideLoading()

    await nextTick(()=>{
        delete formDrawerData.id
    })
}

const drawerSubmit = async () => {
    formRef.value.validate(async (valid) => {
        const data = {...formDrawerData}
        console.log('提交的数据为:')
        console.log(data)
        formDrawerRef.value.showLoading()
        if (!valid) {
            formDrawerRef.value.hideLoading()
            return false
        } else {
            const fn = isAddOrEdit.value ? addRole(data) : updataRole(data)
            await fn
                .then(res => {
                    //后续可以加判断操作
                    console.log(res)
                    formDrawerRef.value.close()
                    //将页面引导到第一页
                    toast(drawerTitile.value + '成功')
                    resetRoleList()
                }).catch(err=>{
                    console.log(err)
                }).finally(() => {
                    formDrawerRef.value.hideLoading()
                })
        }
    })
}

const cleanForm = function(){
    formRef.value.resetFields()
}

//编辑角色结束


//操作栏开始
//删除角色开始
const roleDelete = function (id) {
    showModal('是否要删除该数据?').then(async () => {
        toast('正在删除中...', 'info', false, 3000)
        await deleteRole(id).then(res => {
            toast('删除成功')
            //将页面引导到第一页
            resetRoleList()
        }).catch(err=>{
            console.log(err)
        }).finally(() => {
        })
    })
}
//删除角色结束

//重置操作
const resetRoleList = function(){
    searchRef.value.resetFields()
    page.current = 1
    InitRole()
}
//操作栏结束



</script>
<style scoped>
.roleList-scrollbar {
    /* max-height: 500px; */
    max-width: 1200px;
}
.btn{
    margin-right: 4px;
}
</style>